Traling.SL.TargetTrailing SL and Target
I have seen few requests in PineScripters telegram group asking questions about implementation of trailing stop-loss (SL) and targets. This script is one of the way to implement the same.
This script is developed based on dark color theme and is best viewed using dark color theme.
How and where can this script be used:
The script is built to demonstrate how one can implement the trailing SL and target, so by referring the script one can mimic the approach and add trailing SL and target implementation in their own strategy.
How it works:
To demonstrate the SL and target implementation, i have considered simple EMA crossover strategy.
Key Input Parameters
Method to use for SL/Target trailing:
1. % Based Target and SL - Used to calculate trailing based on parameters defined under group '% Based Target SL'
2. Fixed point Based Target and SL - Used to calculate trailing based on parameters defined under group 'Fixed point Based Target and SL'
% Based Target and SL:
Initial profit % - This is used to calculate target when trade is initiated
Initial SL % - This is used to calculate SL when trade is initiated
Initiate trailing % - This parameter determines, when to start trailing SL and target.
Trail profit by % - Target would be trailed by % specified as this parameter
Trail SL by % - SL would be trailed by % specified as this parameter
e.g.
Trade type: - Long
Trade price: 10000
initial profit %: 1
Initial SL %: 1
Initiate trailing %: 0.5
Trail profit by %: 0.3
Trail SL by %: 0.4
Calculations based on above:
initial profit %: 10100 (trade price + 1%)
Initial SL %: 9900 (trade price - 1%)
Initiate trailing %: 10049.5 (initial profit - 0.5%)
Trail profit by %: 10130 (initial profit + 0.3%)
Trail SL by %: 9939.6 (initial SL + 0.4%)
For next iteration of Trailing SL and target above calculated values will be taken as a base and next set of values will be calculated. these calculations will continue till the trade is exited either on price reaching profit or SL point.
Fixed point Based Target and SL:
Initial profit target points - To derive initial target, parameter value is added to trade price in case of long trade.
Initial SL points - To derive SL point, parameter value is subtracted from trade price
Initiate trailing points - To derive start of trailing logic, parameter value is subtracted from initial profit point.
Trail profit by points - In case of long trade, parameter value is added to the profit target to derive new trailed profit target.
Trail SL by % - In case of long trade, parameter value is added to the SL initial point to derive new trailed SL.
Calculation of Trailing SL and target will continue till the trade is exited either on price reaching profit or SL point.
Plots displayed on the chart:
Apart from default trade markings i have added 3 shapes on the chart to describe working of Trailing SL and targets.
Diamond shape marks - These are added on the chart when trade is initiated. These shapes gives additional trade information by way of 'tooltip'. This information can be viewed by placing mouse pointer on the shape.
Circle shape marks - These are added on the chart whenever Trailing SL and targets are calculated. These shapes gives additional trade information by way of 'tooltip'. This information can be viewed by placing mouse pointer on the shape. You will also notice a number displayed just above or below circle denoting Trailing iteration.
Labels up and label down shapes - These are dynamically placed on the chart whenever trade is in progress. These labels will display ongoing trades, Target and SL points.
Pesquisar nos scripts por "the script"
EHMA Range StrategyThis script is a modified version of @borserman's script for the Exponential Hull Moving Average
All credit for the EHMA goes to him :)
In addition to the EHMA, this script works with a range around the EHMA (which can be modified), in an attempt to be robust against fake signals. Many times a bar will close below a moving average, only to reverse again the next bar, which eats away at your profits. Especially on shorter timeframes, but also on choppy longer timeframes this can make a strategy unattractive to use.
With the range around the EHMA, the strategy only enters a long/exit-short position if a bar crosses above the upper range. Vice versa, it only enters a short/exit-long position if a bar crosses below the lower range. This avoids positions if bars behave choppy within the EHMA range & only enters a position if the market is confident in it's direction. Having said that, fakeouts are still possible, but a lot less frequent. Having backtested this strategy vs the regular EHMA strategy (and having experimented with various settings), this version seems to be a lot more robust & profitable!
Disclaimer
Please remember that past performance may not be indicative of future results.
Due to various factors, including changing market conditions, the strategy may no longer perform as good as in historical backtesting.
This post and the script don’t provide any financial advice.
CRYPTO TRADING BOT - 1min SCALPING LONG/SHORTHOW IT WORKS
The core concept behind the script is the determination of the current market mood in sense of creating a trendline indicator using EMA / SMA .
By using this trend indication alongside RSI / MACD value range, we are able to enter/exit the market in both directions: LONG and SHORT .
In case of confirmed false signals, we try to catch up the next good opportunity to minimise loss and to close the current trade.
If the chance for a good countertrade is given at this point, the market is going to be entered reversely.
Should the market move incredibly fast against our trade direction, we use proven Stop-loss targets, to bring our children into safety.
As many others, we could tell you now, that we used state-of-the-art machine learning algorithms
as well as highly sophisticated methods to gain our results.
As a fact, we started with an idea, using simple and common trading tools/indicators,
as a solid ground. We did not want to reinvent the wheel and it paid off.
GET A WORKING SCRIPT
The algorithm we are using has initially been created with a self-developed backtesting software.
To be able to deliver gas to our engine, we have bought a huge amount of OHLCV data for the 1min chart.
After many exhausting and frustrating weeks of our workflow-rotation (develop, fail, fix, test, repeat)
we finally got confirmation for all of our conditions/expectations, so we translated our algorithm into pine-code.
THE RESULTS
Since we have been using our Pine-Strategy alongside our backtesting software , we checked all the results provided by TradingView
and our tool to be 100% sure every outcome, every entry and every exit is exactly the same.
We did this for several months and since 2021 June we have been using it with real Alerts, coped to our binance account.
Below, you will find how the performance for the previous months looked like (every trade was made with 100% of the capital, of course using proper stop loss and take profit):
September 2020: 15.18%
October 2020: 36.17%
November 2020: 15.12%
December 2020: 48.58%
January 2021: 150.10%
February 2021: 45.96%
March 2021: 46.48%
April 2021: 4.96%
May 2021: 43.48%
June 2021: -28.99%
Juli 2021: 15.63%
August 2021 (so far): 11.57%
Accumulated Profit: 1,979.01%
To prove our results, we will link an excel sheet for every trade that was made within this timerange.
Link: docs.google.com
ABOUT US
We are two good friends, both incredibly interested in mathematics, software engineering, AI and algorithmics. After getting introduced into the crypto space
by a common friend, we started figuring out that there is a pattern behind every big or small move which happens in an asset.
This is where the passion for creating a CRYPTO TRADING BOT began. It was our goal, to create this script for the 1min Timeframe, so the software can react quickly when a
big or small move is happening - this is why it is called a SCALPING SCRIPT .
We are incredibly proud of this script and would like to share it with this amazing community - just hit us up on TradingView!
Zendog V2 backtest DCA bot 3commasHi everyone,
After a few iterations and additional implemented features this version of the Backtester is now open source.
The Strategy is a Backtester for 3commas DCA bots. The main usage scenario is to plugin your external indicator, and backtest it using different DCA settings.
Before using this script please make sure you read these explanations and make sure you understand how it works.
Features:
- Because of Tradingview limitations on how orders are grouped into Trades, this Strategy statistics are calculated by the script, so please ignore the Strategy Tester statistics completely
Statistics Table explained:
- Status: either all deals are closed or there is a deal still running, in which case additional info
is provided below, as when the deal started, current PnL, current SO
- Finished deals: Total number of closed deals both Winning and Losing.
A deal is comprised as the Base Order (BO) + all Safety Orders (SO) related to that deal, so this number
will be different than the Strategy Tester List of Trades
- Winning Deals: Deal ended in profit
- Losing deals: Deals ended with loss due to Stop Loss. In the future I might add a Deal Stop condition to
the script, so that will count towards this number as well.
- Total days ( Max / Avg days in Deal ):
Total Days in the Backtest given by either Tradingview limitation on the number of candles or by the
config of the script regarding "Limit Date Range".
Max Days spent in a deal + which period this happened.
Avg days spent in a deal.
- Required capital: This is the total capital required to run the Backtester and it is automatically calculated by
the script taking into consideration BO size, SO size, SO volume scale. This should be the same as 3commas.
This number overwrites strategy.initial_capital and is used to calculate Profit and other stats, so you don't need
to update strategy.initial_capital every time you change BO/SO settings
- Profit after commission
- Buy and Hold return: The PnL that could have been obtained by buying at the close of the first candle of the
backtester and selling at the last.
- Covered deviation: The % of price move from initial BO order covered by SO settings
- Max Deviation: Biggest market % price move vs BO price, in the other direction (for long
is down, for short it is up)
- Max Drawdown: Biggest market % price move vs Avg price of the whole Trade (BO + any SO), in the other
direction (for long price goes down, for short it goes up)
This is calculated for the whole Trade so it is different than List of Trades
- Max / Avg bars in deal
- Total volume / Commission calculated by the strategy. For correct commission please set Commission in the
Inputs Tab and you may ignore Properties Tab
- Close stats for deals: This is a list of how many Trades were closed at each step, including Stop Loss (if
configured), together with covered deviation for that step, the number of deals, and the percentage of this
number from all the deals
TODO: Might add deal avg value for each step
- Settings Table that can be enabled / disabled just to have an overview of your configs on the chart, this is a
drawn on bottom left
- Steps Table similar to 3commas, this is also drawn on bottom left, so please disable Settings table if you want
to see this one
TODO: Might add extra stats here
- Deal start condition: built in RSI-7 or plugin any external indicator and compare with any value the indicator plots
(main purpose of this strategy is to connect your own studies, so using external indicator is recommended)
- Base order and safety orders configs similar to 3commas (order size, percent deviation, safety orders,
percent scale and volume scale)
- Long and Short
- Stop Loss
- Support for Take profit from base order or from Total volume of the deal
- Configs help (besides self explanatory):
- Chart theme: Adjust according to the theme you run on. There is no way to detect theme at the moment.
This adjust different colors
- Deal Start Type: Either a builtin RSI7 or "External indicator"
- Indicator Source an value: If using External Indicator then select source, comparison and value.
For example you could start a deal when Volume is greater than xxxx, or code a custom indicator that plots
different values based on your conditions and test those values
- Visuals / Decimals for display: Adjust according to your symbol
- BO Entry Price for steps table: This is the BO start deal price used to calculate the steps in the table
Ticker Pulse Meter + Fear EKG StrategyDescription
The Ticker Pulse Meter + Fear EKG Strategy is a technical analysis tool designed to identify potential entry and exit points for long positions based on price action relative to historical ranges. It combines two proprietary indicators: the Ticker Pulse Meter (TPM), which measures price positioning within short- and long-term ranges, and the Fear EKG, a VIX-inspired oscillator that detects extreme market conditions. The strategy is non-repainting, ensuring signals are generated only on confirmed bars to avoid false positives. Visual enhancements, such as optional moving averages and Bollinger Bands, provide additional context but are not core to the strategy's logic. This script is suitable for traders seeking a systematic approach to capturing momentum and mean-reversion opportunities.
How It Works
The strategy evaluates price action using two key metrics:
Ticker Pulse Meter (TPM): Measures the current price's position within short- and long-term price ranges to identify momentum or overextension.
Fear EKG: Detects extreme selling pressure (akin to "irrational selling") by analyzing price behavior relative to historical lows, inspired by volatility-based oscillators.
Entry signals are generated when specific conditions align, indicating potential buying opportunities. Exits are triggered based on predefined thresholds or partial position closures to manage risk. The strategy supports customizable lookback periods, thresholds, and exit percentages, allowing flexibility across different markets and timeframes. Visual cues, such as entry/exit dots and a position table, enhance usability, while optional overlays like moving averages and Bollinger Bands provide additional chart context.
Calculation Overview
Price Range Calculations:
Short-Term Range: Uses the lowest low (min_price_short) and highest high (max_price_short) over a user-defined short lookback period (lookback_short, default 50 bars).
Long-Term Range: Uses the lowest low (min_price_long) and highest high (max_price_long) over a user-defined long lookback period (lookback_long, default 200 bars).
Percentage Metrics:
pct_above_short: Percentage of the current close above the short-term range.
pct_above_long: Percentage of the current close above the long-term range.
Combined metrics (pct_above_long_above_short, pct_below_long_below_short) normalize price action for signal generation.
Signal Generation:
Long Entry (TPM): Triggered when pct_above_long_above_short crosses above a user-defined threshold (entryThresholdhigh, default 20) and pct_below_long_below_short is below a low threshold (entryThresholdlow, default 40).
Long Entry (Fear EKG): Triggered when pct_below_long_below_short crosses under an extreme threshold (orangeEntryThreshold, default 95), indicating potential oversold conditions.
Long Exit: Triggered when pct_above_long_above_short crosses under a profit-taking level (profitTake, default 95). Partial exits are supported via a user-defined percentage (exitAmt, default 50%).
Non-Repainting Logic: Signals are calculated using data from the previous bar ( ) and only plotted on confirmed bars (barstate.isconfirmed), ensuring reliability.
Visual Enhancements:
Optional moving averages (SMA, EMA, WMA, VWMA, or SMMA) and Bollinger Bands can be enabled for trend context.
A position table displays real-time metrics, including open positions, Fear EKG, and Ticker Pulse values.
Background highlights mark periods of high selling pressure.
Entry Rules
Long Entry:
TPM Signal: Occurs when the price shows strength relative to both short- and long-term ranges, as defined by pct_above_long_above_short crossing above entryThresholdhigh and pct_below_long_below_short below entryThresholdlow.
Fear EKG Signal: Triggered by extreme selling pressure, when pct_below_long_below_short crosses under orangeEntryThreshold. This signal is optional and can be toggled via enable_yellow_signals.
Entries are executed only on confirmed bars to prevent repainting.
Exit Rules
Long Exit: Triggered when pct_above_long_above_short crosses under profitTake.
Partial exits are supported, with the strategy closing a user-defined percentage of the position (exitAmt) up to four times per position (exit_count limit).
Exits can be disabled or adjusted via enable_short_signal and exitPercentage settings.
Inputs
Backtest Start Date: Defines the start of the backtesting period (default: Jan 1, 2017).
Lookback Periods: Short (lookback_short, default 50) and long (lookback_long, default 200) periods for range calculations.
Resolution: Timeframe for price data (default: Daily).
Entry/Exit Thresholds:
entryThresholdhigh (default 20): Threshold for TPM entry.
entryThresholdlow (default 40): Secondary condition for TPM entry.
orangeEntryThreshold (default 95): Threshold for Fear EKG entry.
profitTake (default 95): Exit threshold.
exitAmt (default 50%): Percentage of position to exit.
Visual Options: Toggle for moving averages and Bollinger Bands, with customizable types and lengths.
Notes
The strategy is designed to work across various timeframes and assets, with data sourced from user-selected resolutions (i_res).
Alerts are included for long entry and exit signals, facilitating integration with TradingView's alert system.
The script avoids repainting by using confirmed bar data and shifted calculations ( ).
Visual elements (e.g., SMA, Bollinger Bands) are inspired by standard Pine Script practices and are optional, not integral to the core logic.
Usage
Apply the script to a chart, adjust input settings to suit your trading style, and use the visual cues (entry/exit dots, position table) to monitor signals. Enable alerts for real-time notifications.
Designed to work best on Daily timeframe.
Momentum - Strategy ScriptBased on the bult-in momentum script, I took the liberty of updating it, adding two features.
First, I would like to see the momentum oscillator showing percentage values, rather than absolute values. Visually facilitating analysis in long-term graphs.
Second, just for fun*.
I don't know how to explain the reason exactly, but for the strategy bult-in script, I didnt like the formula of "mom1" calculation.
So I changed it for a formula that made the most sense to me.
In any case, the original script remains in the code, optionally disabling the "percent" option and selecting the MOM1 option in the "MOM Choice" field, for the purpose of study and comparisons.
The script below is opened for study and any suggestions will be welcome.
I hope it can help the community.
It's just the beginning.
Study only purpose.
I tried to follow the code conventions found in the link below.
www.pinecoders.com
Altcoin correlation MeterDear TV'ers,
Hereby a script where the relative strength of an (in this case) altcoin is measured. The script produces a correlation between the altcoin and total altcoin market (Total2 index, see script). Using this script you can see when there is a strong correlation between the two and when there isn't. Moreover, it also produces long/short signals using hull moving average crossover.
Long signals are produced when correlation is below 0 and the hma of the pair is higher than the lagging hma.
Short signals are produced when correlation is below 0 and the hma of the pair is lower than the lagging hma.
Short/Long is closed after correlation is going back towards a set correlation target as well as the Take profit percentage is reached.
In the above example the script is applied to one of my favorite altcoin projects (rose).
Looking forward to feedback/suggestions.
Bitlinc MARSI Study AST w/ Take Profit & Stop loss - beta 0.1This script is beta 0.1 - will update as soon as the script is tradable
This script is based on AST on a 10 minute timeframe. You can change the asset and the timeframe for any asset you want to trade, but for it to work correct ALL settings have to be testes in the Strategy section of the TradingView. Each assets and timeframe require a different mixture of settings. This is NOT a one settings fits all trading for all assets on any timeframe. Below are the settings and explanation on how it works.
How it fires a buy / sell:
The script will plot an RSI with upper and lower bands in a separate indicator window. The idea behind this script is to fire a LONG when MA crosses OVER lower band and fire a SHORT when the MA crosses under the lower band. Each order that fires is an OCO (Order Cancels Order) for pyramiding.
Settings:
You have full control of these settings as mentioned above, you must configure every part of this script for each asset and timeframe you trade.
- Length of MA
- Length
- Upper bands of RSI
- Lower bands of RSI
- Take profit percentage
- Stop loss percentage
- Month to start and end the strategy (within 2020)
- Day to start and end the strategy (within 2020)
- Quantity type
- Slippage
- Pyramiding
***Remember that after the signal to enter or exit a trade is fired, the alert will trigger AFTER the close of the candle that caused the tigger to fire
Low Scanner strategy cryptoThis is the last script of the Low scanner series
I have shown in script 1 the best strategy for stocks on 1 hour
script for forex 1 hour (if you look on comments you will find settings which are perfect for low TF (1 min system )
This strategy is the perfect weapen for crypto
no repaint as I shown the scanner do not use security
this system will buy and sell about every 1000 min in the end you will getyour profit which is progressive
set to 1,2,3, and 5 % where each time you take 25% of equaty out
as I shown before the power of the progresive take and my scanner make it best
the scnner serach for low point using my special RSI system with no repaint MTF
every time we get our profit out
the scanner will find us new low to start cycle again
so invite me for coffe if you like this system
thanks to TV that allow donation:)
so this is example of smart strategy that beat the odds
try on major crypto assets (it nice system )
without the script of adolgov
this system was not possible so I would like to thank him very much that he share with us his great script
XPloRR S&P500 Stock Market Crash Detection Strategy v2XPloRR S&P500 Stock Market Crash Detection Strategy v2
Long-Term Trailing-Stop strategy detecting S&P500 Stock Market Crashes/Corrections and showing Volatility as warning signal for upcoming crashes
Detecting or avoiding stock market crashes seems to be the 'Holy Grail' of strategies.
Since none of the strategies that I tested can beat the long term Buy&Hold strategy, the purpose was to detect a stock market crash on the S&P500 and step out in time to minimize losses and beat the Buy&Hold strategy. So beat the Buy&Hold strategy with around 10 trades. 100% capitalize sold trade into new trade.
With the default parameters the strategy generates 10262% profit (starting at 01/01/1962 until release date), with 10 closed trades, 100% profitable, while the Buy&Hold strategy only generates 3633% profit, so this strategy beats the Buy&Hold strategy by 2.82 times !
Also the strategy detects all major S&P500 stock market crashes and corrections since 1962 depending on the Trailing Stop Smoothness parameter, and steps out in time to cut losses and steps in again after the bottom has been reached. The 5 major crashes/corrections of 1987, 1990, 2001, 2008 and 2010 were successfully detected with the default parameters.
The script was first released on November 03 2019 and detected the Corona Crash on March 04 2020 with a Volatility crash-alert and a Sell crash-alert.
I have also created an Alerter Study Script based on the engine of this script, which generates Buy, Sell and Volatility signals.
If you are interested in this Alerter version script, please drop me a mail.
The script shows a lot of graphical information:
the Close value is shown in light-green. When the Close value is temporarily lower than the Buy value, the Close value is shown in light-red. This way it is possible to evaluate the virtual losses during the current trade.
the Trailing Stop value is shown in dark-green. When the Sell value is lower than the Buy value, the last color of the trade will be red (best viewed when zoomed)
the EMA and SMA values for both Buy and Sell signals are shown as colored graphs
the Buy signals are labeled in blue and the Sell signals are labeled in purple
the Volatility is shown below in green and red. The Alert Threshold (red) is default set to 2 (see Volatility Threshold parameter below)
How to use this Strategy?
Select the SPX (S&P500) graph and add this script to the graph.
Look in the strategy tester overview to optimize the values Percent Profitable and Net Profit (using the strategy settings icon, you can increase/decrease the parameters), then keep using these parameters for future Buy/Sell signals on the S&P500.
More trades don't necessarily generate more overall profit. It is important to detect only the major crashes and avoid closing trades on the smaller corrections. Bearing the smaller corrections generates a higher profit.
Watch out for the Volatility Alerts generated at the bottom (red). The Threshold can by changed by the Volatility Threshold parameter (default=2% ATR). In almost all crashes/corrections there is an alert ahead of the crash.
Although the signal doesn't predict the exact timing of the crash/correction, it is a clear warning signal that bearish times are ahead!
The correction in December 2018 was not a major crash but there was already a red Volatility warning alert. If the Volatility Alert repeats the next weeks/months, chances are higher that a bigger crash or correction is near. As can be seen in the graphic, the deeper the crash is, the higher and wider the red Volatility signal goes. So keep an eye on the red flag!
Here are the parameters:
Fast MA Buy: buy trigger when Fast MA Buy crosses over the Slow MA Buy value (use values between 10-20)
Slow MA Buy: buy trigger when Fast MA Buy crosses over the Slow MA Buy value (use values between 21-50)
Minimum Buy Strength: minimum upward trend value of the Fast MA Buy value (directional coefficient)(use values between 10-100)
Fast MA Sell: sell trigger when Fast MA Sell crosses under the Slow MA Sell value (use values between 10-20)
Slow MA Sell: sell trigger when Fast MA Sell crosses under the Slow MA Sell value (use values between 21-50)
Minimum Sell Strength: minimum downward trend value of the Fast MA Sell value (directional coefficient)(use values between 10-100)
Trailing Stop ATR: trailing stop % distance from the smoothed Close value (use values between 2-20)
Trailing Stop Smoothness: MA value for smoothing out the Trailing Stop close value
Buy On Start Date: force Buy on start date even without Buy signal (default: true)
Sell On End Date: force Sell on end date even without Sell signal (default: true)
Volatility EMA Period: MA value of the Volatility value (default 15)
Volatility Threshold: Threshold value to change volatility graph to red (default 2)
Volatility Graph Scaler: Scaling of the volatility graph (default 5)
Important : optimizing and using these parameters is no guarantee for future winning trades!
Strategy VS Buy & HoldSUMMARY:
A strategy wrapper that makes a detailed and visual comparison between a given strategy and the buy & hold returns of the traded security.
DESCRIPTION:
TradingView has a "Buy & Hold Return" metric in the strategy tester that is often enough to assess how our strategy compares to a simple buy hold. However, one may want more information on how and when your strategy beats or is beaten by a simple buy & hold strategy. This script aims to show such detail by providing a more comprehensive metrics and charting the profit/loss of the given strategy against buy & hold.
As seen in the script, it plots/draws 4 elements:
1) Strategy P/L: strategy net profit + strategy open profit
2) Buy & Hold P/L: unrealized return
3) Difference: Strategy P/L - Buy & Hold P/L
4) Strategy vs Buy Hold Stats
> Percent of bars strategy P/L is above Buy & Hold
> Percent of bars strategy P/L is below Buy & Hold
> All Time Average Difference
ADJUSTABLE PARAMETERS:
All labels/panels can be disabled by unchecking these two options:
>bnh_info_panel = input(true, title='Enable Info Panel')
>bnh_indicator_panel = input(true, title='Enable Indicator Panel')
Comparison Date Range can be changed to better isolate specific areas:
>From Year, From Month, From Day
default: 1970 01 01
>To Year, To Month, To Day
default: 2050 12 31
Default settings basically covers all historical data.
HOW TO USE:
The default script contains a simple 50-200 SMA cross strategy, just delete and replace it. Those are everything between these lines:
/////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////STRATEGY SCRIPT START//////////////////////////////////
(STRATEGY SCRIPT GOES HERE)
//////////////////////////////STRATEGY SCRIPT END////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
Removing all plots and drawings from your strategy is advisable.
If you are going to use the Comparison Date Range, apply "bnh_timeCond" to your strategy to align the dates. A sample on how it’s applied can be seen on the Placeholder MA cross strategy.
Note: bnh_timeCond returns a boolean series
TradingView Alerts to MT4 MT5 + dynamic variables NON-REPAINTINGAccidentally, I’m sharing open-source profitable Forex strategy. Accidentally, because this was aimed to be purely educational material. A few days ago TradingView released a very powerful feature of dynamic values from PineScript now being allowed to be passed in Alerts. And thanks to TradingConnector, they could be instantly executed in MT4 or MT5 platform of any broker in the world. So yeah - TradingConnector works with indices and commodities, too.
The logic of this EURUSD 6h strategy is very simple - it is based on Stochastic crossovers with stop-loss set under most recent pivot point. Setting stop-loss with surgical precision is possible exactly thanks to allowance of dynamic values in alerts. TradingConnector has been also upgraded to take advantage of these dynamic values and it now enables executing trades with pre-calculated stop-loss, take-profit, as well as stop and limit orders.
Another fresh feature of TradingConnector, is closing positions only partly - provided that the broker allows it, of course. A position needs to have trade_id specified at entry, referred to in further alerts with partial closing. Detailed spec of alerts syntax and functionalities can be found at TradingConnector website. How to include dynamic variables in alert messages can be seen at the very end of the script in alertcondition() calls.
The strategy also takes commission into consideration.
Slippage is intentionally left at 0. Due to shorter than 1 second delivery time of TradingConnector, slippage is practically non-existing. This can be achieved especially if you’re using VPS server, hosted in the same datacenter as your brokers’ servers. I am using such setup, it is doable. Small slippage and spread is already included in commission value.
This strategy is NON-REPAINTING and uses NO TRAILING-STOP or any other feature known to be faulty in TradingView backtester. Does it make this strategy bulletproof and 100% success-guaranteed? Hell no! Remember the no.1 rule of backtesting - no matter how profitable and good looking a script is, it only tells about the past. There is zero guarantee the same strategy will get similar results in the future.
To turn this script into study so that alerts can be produced, do 2 things:
1. comment “strategy” line at the beginning and uncomment “study” line
2. comment lines 54-59 and uncomment lines 62-65.
Then add script to the chart and configure alerts.
This script was build for educational purposes only.
Certainly this is not financial advice. Anybody using this script or any of its parts in any way, must be aware of high risks connected with trading.
Thanks @LucF and @a.tesla2018 for helping me with code fixes :)
[M10] MA Squeeze Funding Trader [Backtest]Hey all,
My latest script combines a few indicators together in order to create a powerful, more reliable automation of trading based on short-term Trend direction and BixMex Funding with various filters, including three Moving Averages, Keltner Channels and Bollinger Bands.
This script will buy/sell based on the current trend determined by three customisable moving averages, with the option to apply the following filters:
Moving Average Filter: Will only buy/sell once the price overextends above/below moving averages, with reversal likely.
BitMex Funding: Will only buy/sell based on BitMex's current funding. The price is often found to trend with funding.
Squeeze Indicator: A combination of Keltner Channels and Bollinger Bands find areas with stable price movement for optimal entry points.
The script will exit a position upon a reversal signal from the three moving averages.
This script appears to work very well in ranging markets, however will not always perform so well in trending markets. Applying the squeeze and funding filters will reduce the frequency at which positions are entered, however has proven powerful in preventing losing trades.
I have also created an alerts version of this script available at no cost on my page - enjoy!
Any questions? Let me know!
[M10] Quad MA Trend ScalperFour adjustable moving averages set in order to produce buy and sell signals, works best on smaller timeframes from my backtesting, 10M - 30M seems optimal for scalping.
The idea behind this script is to only enter positions that are following the trend in order to minimise drawdown and decrease risk when using leverage.
The script will only enter long positions when MA crossover occurs above the Long MA 2.
The script will exit a long position when MA Short crosses below Long MA 1.
The script will only enter short positions when MA cross under occurs below the Long MA 2.
The script will exit a short position when MA Short crosses below Long MA 1.
Gunbot Deluxe Tuners BERevision 18
Gunbot Deluxe Tuners BE (Black Edition) is the official Gunthy version of Gunbot Deluxe Tuners.
It is an all in one script simulation of Gunbot with the ability to optimize Gunbot settings through backtesting any combination of the script's included buy / sell strategies along with extra conditions and trailing options.
The companion script allows user to automatically send alerts directly to Gunbot through the Gunbot TradingView add-on.
Available only to verified Gunbot owners. No exceptions. Anyone interested in obtaining this script must contact either their official Gunbot reseller or me privately.
No public requests or donations for access to this script will be granted. No exceptions.
NOTICE: By requesting access to this script you acknowledge that you have read and understood that this is for research purposes only and neither I or Gunthy are responsible for any financial losses you may incur by using this script!
TradeSpot Pro || Accompanying Strategy indicatorTradeSpot Pro
Overview
This script is an accompaniment to the existing TradeSpot Pro || All Purpose Advanced Trading Indicator
This script is for swing trading with longs, primarily on Binance / Kucoin / Coinbase and other crypto exchanes but is not limited to those markets. The details of what logic is behind the script can be found on the indicator version linked above.
Bags? This script has been tweaked and modified to completely destroy bear markets despite being focused on longs, see the BTCUSD image or PM me for any chart of your liking. I dislike indicators that show an amazing looking run in a bull market but in bear markets they fall apart - well with TradeSpot Pro that is not the case, it is completely market agnostic
Access
For details of access please join the TradeSpot community server where we can sort you out: discord.gg
Alternatively PM me if you would like to directly purchase the strategy and paired indicator.
Euro/Dollar StrengthHey all,
I have been using this strategy for a while, just like my last script (XAG/USD Spread) this utilizes my 'holy grail' method of basket weighting (aka why the script is protected).
This script just looks for periods of time when the euro is gaining against a basket of currencies and the USD is losing vs the basket (and vice versa)
I use this script on the 4H time frame; although I can make this script work for almost any currency pair and time frame I have the most success with EURUSD 4H.
I personally use 3 of these 'strength meters' in triangular arbitrage for EU UJ and EJ
if I get good feedback and support I may publish the other 2 of the 'triangle' or even make a version that automatically detects the currency pair and adjusts settings accordingly.
Thanks for the feedback and support, hope this helps!
Snoop
Babanov_DOTUSDT V2🧪 Deep Backtest Results (DOT 5-Min Strategy)
Backtest conducted on DOTUSDT.P (Bybit) using a 5-minute chart timeframe over several weeks of data.
! imgur.com
⚠️ Важно: Инструкции за правилна употреба на скрипта!
Ако искате да използвате този скрипт с webhook alerts за автоматична търговия, моля, обърнете внимание на следните стъпки:
✅ 1. Активирайте "Live Trading Mode"
Преди да създадете какъвто и да е alert, отидете в таба "Inputs" и задължително активирайте опцията "Live Trading Mode". Без нея скриптът няма да изпраща правилни сигнали.
✅ 2. Въведете търговската сума в USD
В таба "Properties", въведете сумата в USD, която ботът ще използва за търговия с DOT.
- Препоръчително е сумата да бъде такава, която може да бъде разделена на 50 (например 50, 100, 150, 200 и т.н.), за да се гарантира коректно управление на позициите и обемите при търговия.
✅ 3. Препоръчителна платформа: Bybit - BYBIT:DOTUSDT.P
Скриптът е оптимизиран и тестван за търговия на Bybit. Използването му на други платформи може да доведе до различни резултати, тъй като графиките и ценовите движения може да се различават.
-----------------------------------------------------------------------------------------------
⚠️ Important: Instructions for Proper Use of This Script
If you want to use this script with webhook alerts for automated trading, please follow the steps below carefully:
✅ 1. Enable "Live Trading Mode"
Before creating any alerts, go to the "Inputs" tab and make sure to enable the "Live Trading Mode" option.
Without it, the script will not generate correct trading signals.
✅ 2. Enter Your Trading Amount in USD
In the "Properties" tab, enter the amount in USD that the bot will use for DOT trading.
It is strongly recommended to enter an amount that can be divided by 50 (e.g., 50, 100, 150, 200, etc.) to ensure proper position sizing and trade management.
✅ 3. Recommended Exchange: Bybit - BYBIT:DOTUSDT.P
The script is optimized and tested specifically for Bybit.
Using it on other exchanges may result in different outcomes due to variations in chart data and price movements.
Babanov_XRPUSDT V2🧪 Deep Backtest Results (XRP 5-Min Strategy)
Backtest conducted on XRPUSDT.P (Bybit) using a 5-minute chart timeframe over several weeks of data.
! imgur.com
⚠️ Важно: Инструкции за правилна употреба на скрипта!
Ако искате да използвате този скрипт с webhook alerts за автоматична търговия, моля, обърнете внимание на следните стъпки:
✅ 1. Активирайте "Live Trading Mode"
Преди да създадете какъвто и да е alert, отидете в таба "Inputs" и задължително активирайте опцията "Live Trading Mode". Без нея скриптът няма да изпраща правилни сигнали.
✅ 2. Въведете търговската сума в USD
В таба "Properties", въведете сумата в USD, която ботът ще използва за търговия с XRP.
- Препоръчително е сумата да бъде такава, която може да бъде разделена на 50 (например 50, 100, 150, 200 и т.н.), за да се гарантира коректно управление на позициите и обемите при търговия.
✅ 3. Препоръчителна платформа: Bybit - BYBIT:XRPUSDT.P
Скриптът е оптимизиран и тестван за търговия на Bybit. Използването му на други платформи може да доведе до различни резултати, тъй като графиките и ценовите движения може да се различават.
-----------------------------------------------------------------------------------------------
⚠️ Important: Instructions for Proper Use of This Script
If you want to use this script with webhook alerts for automated trading, please follow the steps below carefully:
✅ 1. Enable "Live Trading Mode"
Before creating any alerts, go to the "Inputs" tab and make sure to enable the "Live Trading Mode" option.
Without it, the script will not generate correct trading signals.
✅ 2. Enter Your Trading Amount in USD
In the "Properties" tab, enter the amount in USD that the bot will use for XRP trading.
It is strongly recommended to enter an amount that can be divided by 50 (e.g., 50, 100, 150, 200, etc.) to ensure proper position sizing and trade management.
✅ 3. Recommended Exchange: Bybit - BYBIT:XRPUSDT.P
The script is optimized and tested specifically for Bybit.
Using it on other exchanges may result in different outcomes due to variations in chart data and price movements.
Babanov_SOLUSDT V2🧪 Deep Backtest Results (SOL 5-Min Strategy)
Backtest conducted on SOLUSDT.P (Bybit) using a 5-minute chart timeframe over several weeks of data.
! imgur.com
⚠️ Важно: Инструкции за правилна употреба на скрипта!
Ако искате да използвате този скрипт с webhook alerts за автоматична търговия, моля, обърнете внимание на следните стъпки:
✅ 1. Активирайте "Live Trading Mode"
Преди да създадете какъвто и да е alert, отидете в таба "Inputs" и задължително активирайте опцията "Live Trading Mode". Без нея скриптът няма да изпраща правилни сигнали.
✅ 2. Въведете търговската сума в USD
В таба "Properties", въведете сумата в USD, която ботът ще използва за търговия с SOL.
- Препоръчително е сумата да бъде такава, която може да бъде разделена на 50 (например 50, 100, 150, 200 и т.н.), за да се гарантира коректно управление на позициите и обемите при търговия.
✅ 3. Препоръчителна платформа: Bybit - BYBIT:SOLUSDT.P
Скриптът е оптимизиран и тестван за търговия на Bybit. Използването му на други платформи може да доведе до различни резултати, тъй като графиките и ценовите движения може да се различават.
-----------------------------------------------------------------------------------------------
⚠️ Important: Instructions for Proper Use of This Script
If you want to use this script with webhook alerts for automated trading, please follow the steps below carefully:
✅ 1. Enable "Live Trading Mode"
Before creating any alerts, go to the "Inputs" tab and make sure to enable the "Live Trading Mode" option.
Without it, the script will not generate correct trading signals.
✅ 2. Enter Your Trading Amount in USD
In the "Properties" tab, enter the amount in USD that the bot will use for SOL trading.
It is strongly recommended to enter an amount that can be divided by 50 (e.g., 50, 100, 150, 200, etc.) to ensure proper position sizing and trade management.
✅ 3. Recommended Exchange: Bybit - BYBIT:SOLUSDT.P
The script is optimized and tested specifically for Bybit.
Using it on other exchanges may result in different outcomes due to variations in chart data and price movements.
Babanov_ETHUSDT V2🧪 Deep Backtest Results (ETH 5-Min Strategy)
Backtest conducted on ETHUSDT.P (Bybit) using a 5-minute chart timeframe over several weeks of data.
! imgur.com
⚠️ Важно: Инструкции за правилна употреба на скрипта!
Ако искате да използвате този скрипт с webhook alerts за автоматична търговия, моля, обърнете внимание на следните стъпки:
✅ 1. Активирайте "Live Trading Mode"
Преди да създадете какъвто и да е alert, отидете в таба "Inputs" и задължително активирайте опцията "Live Trading Mode". Без нея скриптът няма да изпраща правилни сигнали.
✅ 2. Въведете търговската сума в USD
В таба "Properties", въведете сумата в USD, която ботът ще използва за търговия с ETH.
- Препоръчително е сумата да бъде такава, която може да бъде разделена на 50 (например 50, 100, 150, 200 и т.н.), за да се гарантира коректно управление на позициите и обемите при търговия.
✅ 3. Препоръчителна платформа: Bybit - BYBIT:ETHUSDT.P
Скриптът е оптимизиран и тестван за търговия на Bybit. Използването му на други платформи може да доведе до различни резултати, тъй като графиките и ценовите движения може да се различават.
-----------------------------------------------------------------------------------------------
⚠️ Important: Instructions for Proper Use of This Script
If you want to use this script with webhook alerts for automated trading, please follow the steps below carefully:
✅ 1. Enable "Live Trading Mode"
Before creating any alerts, go to the "Inputs" tab and make sure to enable the "Live Trading Mode" option.
Without it, the script will not generate correct trading signals.
✅ 2. Enter Your Trading Amount in USD
In the "Properties" tab, enter the amount in USD that the bot will use for ETH trading.
It is strongly recommended to enter an amount that can be divided by 50 (e.g., 50, 100, 150, 200, etc.) to ensure proper position sizing and trade management.
✅ 3. Recommended Exchange: Bybit - BYBIT:ETHUSDT.P
The script is optimized and tested specifically for Bybit.
Using it on other exchanges may result in different outcomes due to variations in chart data and price movements.
Babanov_BTCUSDT V2🧪 Deep Backtest Results (BTC 5-Min Strategy)
Backtest conducted on BTCUSDT.P (Bybit) using a 5-minute chart timeframe over several weeks of data.
! (i.imgur.com)
⚠️ Важно: Инструкции за правилна употреба на скрипта!
Ако искате да използвате този скрипт с webhook alerts за автоматична търговия, моля, обърнете внимание на следните стъпки:
✅ 1. Активирайте "Live Trading Mode"
Преди да създадете какъвто и да е alert, отидете в таба "Inputs" и задължително активирайте опцията "Live Trading Mode". Без нея скриптът няма да изпраща правилни сигнали.
✅ 2. Въведете търговската сума в USD
В таба "Properties", въведете сумата в USD, която ботът ще използва за търговия с BTC.
- Препоръчително е сумата да бъде такава, която може да бъде разделена на 50 (например 50, 100, 150, 200 и т.н.), за да се гарантира коректно управление на позициите и обемите при търговия.
✅ 3. Препоръчителна платформа: Bybit - BYBIT:BTCUSDT.P
Скриптът е оптимизиран и тестван за търговия на Bybit. Използването му на други платформи може да доведе до различни резултати, тъй като графиките и ценовите движения може да се различават.
-----------------------------------------------------------------------------------------------
⚠️ Important: Instructions for Proper Use of This Script
If you want to use this script with webhook alerts for automated trading, please follow the steps below carefully:
✅ 1. Enable "Live Trading Mode"
Before creating any alerts, go to the "Inputs" tab and make sure to enable the "Live Trading Mode" option.
Without it, the script will not generate correct trading signals.
✅ 2. Enter Your Trading Amount in USD
In the "Properties" tab, enter the amount in USD that the bot will use for BTC trading.
It is strongly recommended to enter an amount that can be divided by 50 (e.g., 50, 100, 150, 200, etc.) to ensure proper position sizing and trade management.
✅ 3. Recommended Exchange: Bybit – BYBIT:BTCUSDT.P
The script is optimized and tested specifically for Bybit.
Using it on other exchanges may result in different outcomes due to variations in chart data and price movements.
Babanov_BTCUSDT!!! Important: Instructions for Proper Use of This Script
If you want to use this script with webhook alerts for automated trading, please follow the steps below carefully:
✅ 1. Enable "Live Trading Mode"
Before creating any alerts, go to the "Inputs" tab and make sure to enable the "Live Trading Mode" option.
Without it, the script will not generate correct trading signals.
✅ 2. Enter Your Trading Amount in USD
In the "Properties" tab, enter the amount in USD that the bot will use for BTC trading.
It is strongly recommended to enter an amount that can be divided by 50 (e.g., 50, 100, 150, 200, etc.) to ensure proper position sizing and trade management.
✅ 3. Recommended Exchange: Bybit – BYBIT:BTCUSDT.P
The script is optimized and tested specifically for Bybit.
Using it on other exchanges may result in different outcomes due to variations in chart data and price movements.
-----------------------------------------------------------------------------------------------
!!! Важно: Инструкции за правилна употреба на скрипта!
Ако искате да използвате този скрипт с webhook alerts за автоматична търговия, моля, обърнете внимание на следните стъпки:
✅ 1. Активирайте "Live Trading Mode"
Преди да създадете какъвто и да е alert, отидете в таба "Inputs" и задължително активирайте опцията "Live Trading Mode". Без нея скриптът няма да изпраща правилни сигнали.
✅ 2. Въведете търговската сума в USD
В таба "Properties", въведете сумата в USD, която ботът ще използва за търговия с BTC.
- Препоръчително е сумата да бъде такава, която може да бъде разделена на 50 (например 50, 100, 150, 200 и т.н.), за да се гарантира коректно управление на позициите и обемите при търговия.
✅ 3. Препоръчителна платформа: Bybit - BYBIT:BTCUSDT.P
Скриптът е оптимизиран и тестван за търговия на Bybit. Използването му на други платформи може да доведе до различни резултати, тъй като графиките и ценовите движения може да се различават.
Turtle Trading Strategy (Simplified)This TradingView script is a powerful implementation of the classic Turtle Trading strategy, designed to help traders capitalize on significant market trends. Built using Pine Script, it can function as an indicator to highlight the specific entry and exit signals derived from the Turtle rules, or as a fully automated strategy to execute trades based on these signals. Users can fine-tune critical parameters like the lookback periods for breakouts and exits, enabling them to adapt the strategy to different market conditions and asset classes. The script leverages Pine Script's robust capabilities to accurately calculate and display the Turtle System's core logic, including position sizing based on volatility (ATR), providing a clear and systematic approach to trend-following directly on their TradingView charts.